<?php

class AccountsController extends Exts_Controller_SecureAction {

	public function listAction() {
		$userModel = new Application_Model_Users();
		$query = $userModel->select();
		$this->view->paginator = new Exts_Paginator($query, $this->_page, $this->view);
	}

	public function updateAction() {
		if (!$this->_hasParam('id')) {
			return $this->_redirect('/accounts/list/');
		}
		$form = new Application_Form_User();
		
		$userModel = new Application_Model_Users();
		if ($this->getRequest()->isPost()) {
			$postData = $this->getRequest()->getParams();
			if ($form->isValid($postData)) {
				$bind = $form->getValues();
				try {
					$bind['user_id'] = $this->_getParam('id');
					$id = $userModel->save($bind);
					$userRoleModel = new Exts_Models_UsersRoles();
					$userRoleModel->save($this->_getParam('id'), $bind['role_id']);
					return $this->_redirect('/accounts/list');
				} catch (Exception $e) {
					$this->_helper->flashMessenger(
						'Ocurrio un error revise los datos del formulario'
					);
				}
			}
			$form->populate($form->getValues());
		} else {
			try {
				$bind = $userModel->getFullUser($this->_getParam('id'));
			} catch (Exception $e) {
				throw new Exts_Exception("No se encontro");
				return $this->_redirect('/accounts/list/');
			}
			$bind['role_id'] = $bind['id'];
			$bind['password'] = '';
			$form->populate($bind);

		}

		$form->removeAllDecorator();
		$form->setClassToElement('all', 'input-short');

		// renderer de este form
		$form->setDecorators(
			array(
				array(
					'ViewScript',
					array('viewScript' => 'accounts/form.phtml')
				)
			)
		);
		$this->view->form = $form;
	}

	public function createAction() {

		$form = new Application_Form_User();

		if ($this->getRequest()->isPost()) {
			$postData = $this->getRequest()->getParams();
			if ($form->isValid($postData)) {
				$bind = $form->getValues();
				$userModel = new Application_Model_Users();
				//Validamos que el headoffice no exista con el mismo nombre

				if ($userModel->exists($bind['username'])) {
					$form->username->addErrorMessage("El usuario ya existe");
				} else {
					try {
						$id = $userModel->save($bind);
						$userRoleModel = new Exts_Models_UsersRoles();

						$userRoleModel->save($id, $bind['role_id']);

						return $this->_redirect('/accounts/list');
					} catch (Exception $e) {
						$this->_helper->flashMessenger()
							->addMessage('Ocurrio un error revise los datos del formulario');
					}
				}
			}
			$form->populate($form->getValues());
		}

		$form->removeAllDecorator();
		$form->setClassToElement('all', 'input-short');

		// renderer de este form
		$form->setDecorators(
			array(
				array(
					'ViewScript',
					array('viewScript' => 'accounts/form.phtml')
				)
			)
		);
		$this->view->form = $form;
	}

}